﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

using QuDao;
using FineUICore;
using Kalman;
using Kalman.Extensions;
using AliyunOss;
using Microsoft.AspNetCore.Http;

namespace AdminUI.Pages.BaseData
{
    public partial class VideoEditModel : BaseModel
    {
        readonly AliyunOssClient oss;
        public VideoEditModel(AliyunOssClient ossClient)
        {
            oss = ossClient;
        }

        public void OnGet(int id)
        {
            Current = VideoBO.Instance.GetItem<Video>(id);
        }

        public Video Current { get; set; }

        public IActionResult OnPostSource_SelectedIndexChanged(int selected)
        {
            var video = UIHelper.FileUpload("VideoUrl");
            var live = UIHelper.TextBox("LiveUrl");
            if (selected != 2)
            {
                video.Hidden(false);
                live.Hidden(true);
            }
            else
            {
                video.Hidden(true);
                live.Hidden(false);
            }

            return UIHelper.Result();
        }

        public IActionResult OnPostBtnSubmit_Click(VideoModifyDto dto, IFormFile coverUrl, IFormFile videoUrl, int source, string liveUrl)
        {
            try
            {
                if (coverUrl != null)
                {
                    var img = UploadImage(oss, coverUrl);
                    if (img != null)
                    {
                        dto.CoverUrl = img.OssUrl;
                    }
                }

                if (source > 0)
                {
                    if (videoUrl != null && source == 1)
                    {
                        var file = UploadVideo(oss, videoUrl, 20);
                        if (file != null)
                        {
                            dto.VideoUrl = file.OssUrl;
                            dto.FileSize = (int)file.FileSize;
                        }
                    }
                    else
                    {
                        dto.VideoUrl = liveUrl;
                    }
                }

                VideoBO.Instance.Modify(dto);
                LogAction(ActionType.修改, $"修改视频：{dto.VideoID}-{dto.Memo}");

                FineUICore.PageContext.RegisterStartupScript(ActiveWindow.GetHideRefreshReference());
                //ActiveWindow.HidePostBack();
            }
            catch (Exception ex)
            {
                var msg = ex.Message;
                if (!(ex is AppException && ex.InnerException == null))
                {
                    msg = ex.ToString();
                }

                Alert.Show(msg, "错误信息", MessageBoxIcon.Error);
            }

            return UIHelper.Result();
        }

    }
}